package com.hyz.filter;

import com.alibaba.fastjson.JSON;
import com.hyz.pojo.ResponseResult;
import com.hyz.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author HGD
 * @date 2022/9/16 9:38
 * 当授权失败的时候经过这个类抛出自定义异常
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 授权失败后自定义返回的结果
        ResponseResult<String> responseResult = new ResponseResult<String>(HttpStatus.FORBIDDEN.value(), "您权限不足", null);
        String json = JSON.toJSONString(responseResult);
        WebUtils.renderString(response, json);
    }
}